/*
 * TAN-Manager
 * Copyright (C) 2011 Bernhard Bermeitinger
 * E-Mail: bernhard.bermeitinger@googlemail.com
 * Link:   https://code.google.com/p/tan-management/
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package tan_manager.datahandler;


import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import tan_manager.Constants;

/**
 * This class provides the ability to read a file, returns any line of it and
 * saves when the line was last flagged as deleted with the date when it was flagged.
 *
 * @author Bernhard Bermeitinger
 */
public class FileManager {

    /**
     * File which to edit
     */
    private final String filename;

    private BufferedReader reader;

    /**
     * Contains all lines.
     */
    private ArrayList<String> lines = new ArrayList<String>(200);

    /**
     * Create a new {@code DataGetter} and read all lines of the file in
     * {@code giveFilename}.
     *
     * @param givenFilename {@code String} which points to the file
     * @throws IOException Thrown if file is unaccessible.
     */
    public FileManager(String givenFilename) throws IOException {
        filename = givenFilename;

        File file = new File(filename);

        if (file.exists()) {
            fillBuffer();
        } else {
            file.createNewFile();
        }
    }

    private void fillBuffer() throws IOException {
        reader = new BufferedReader(new FileReader(filename));
        for (String s = reader.readLine(); s != null; s = reader.readLine()) {
            if (s.equals("")) {
                s = "##; no date";
            }
            lines.add(s);
        }
    }

    /**
     * Returns the count of TANs that are in the file.
     *
     * @return count of TANs in the file
     */
    public int getSize() {
        return lines.size();
    }

    /**
     * Returns how many still not used TANs are in the file.
     *
     * @return count of valid TANs in the file
     */
    public int getCountOfValidTANs() {
        int count = 0;
        for (String str : lines) {
            if (!str.startsWith(Constants.DELETION_FLAG)) {
                ++count;
            }
        }
        return count;
    }

    /**
     * Returns the {@code number}th line on the current list.
     * 
     * @param number Line which should be returned.
     * @return line Content of line {@code number}.
     * @throws IOException
     */
    public String getLine(int number) throws IOException {

        // Line 1 is entry 0 in list
        if ((number > 0) && (number <= lines.size())) {
            return lines.get(number - 1);
        } else {
            throw new IllegalArgumentException("Wrong input. Either too high or too low.");
        }
    }

    /**
     * Flags the line {@code number} as deleted and adds the current date
     * to realize later when the line was deleted.
     *
     * @param number Line which should be removed.
     * @param str Content of the line to remove.
     * @throws IOException Thrown if writing is not successful.
     */
    public void flagLineAsUsed(int number, String str) throws IOException {

        // Line 1 is entry 0 in list
        --number;
        StringBuffer toWrite = new StringBuffer();
        BufferedWriter writer = new BufferedWriter(new FileWriter(filename));
        for (int i = 0; i < lines.size(); ++i) {
            if ((i == number) && str.equals(lines.get(i))) {
                toWrite.append(Constants.DELETION_FLAG);
                toWrite.append(lines.get(i));
                toWrite.append(Constants.DELIMITER);
                toWrite.append(currentTime());
                toWrite.append("\n");
            } else {
                if (lines.get(i) == null) {
                    toWrite.append("\n");
                } else {
                    toWrite.append(lines.get(i));
                    toWrite.append("\n");
                }
            }
        }
        writer.write(toWrite.toString());
        writer.close();
    }

    public void write(String str) throws IOException {
        BufferedWriter writer = new BufferedWriter(new FileWriter(filename));
        writer.write(str);
        writer.close();
    }

    /**
     * Returns the current time in the following format:
     * "31.01.2011 16:24"
     *
     * @return Current time
     */
    private static String currentTime() {
        SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy HH:mm");
        return sdf.format(new Date());
    }
}
